﻿using System;
using K9Nano.Dependency;

namespace K9Nano.Caching
{
    public interface ITypedCacheCleanerFactory
    {
        ITypedCacheCleaner Create(Type cachedValueType);

        ITypedCacheCleaner Create<TCachedValue>() where TCachedValue : class;
    }

    public class DefaultTypedCacheCleanerFactory : ITypedCacheCleanerFactory, ISingletonDependency
    {
        private readonly IServiceProvider _serviceProvider;

        public DefaultTypedCacheCleanerFactory(IServiceProvider serviceProvider)
        {
            _serviceProvider = serviceProvider;
        }

        public ITypedCacheCleaner Create(Type cachedValueType)
        {
            var cacheType = typeof(ITypedCache<>).MakeGenericType(cachedValueType);
            return (ITypedCacheCleaner)_serviceProvider.GetService(cacheType);
        }

        public ITypedCacheCleaner Create<TCachedValue>() where TCachedValue : class
        {
            return (ITypedCacheCleaner)_serviceProvider.GetService(typeof(ITypedCache<TCachedValue>));
        }
    }
}